/**
 * Created by jiangxiaowei on 2016/12/23.
 */

'use strict';
let VersionHistory = require('../dao/version-history-model');

let VersionHistoryService = module.exports = {

  addVersionHistory: function (versionHistory) {
    return new Promise((resolve,reject)=>{
      let entity = new VersionHistory(versionHistory);
      entity.save((err,data)=>{
        err ? reject(err) : resolve(data);
      })
    })
  },

  getHistories: async function ({name, pageSize, pageNum}) {
    let _self = this;
    pageSize = parseInt(pageSize);
    pageNum = parseInt(pageNum);
    let versionHistories;
    let totalCount = await _self.getHistoryCount({name});
    if (pageNum > 0) {
      let index = pageNum*pageSize;
      let item = await _self.getLastHistory({name, index});
      let objectId = item && item._id;
      versionHistories = await _self.getHistoriesByPage({name, objectId, pageSize});
    } else {
      versionHistories = await _self.getHistoriesBySkip({name, pageNum, pageSize});
    }

    return {totalCount, versionHistories};
  },

  getHistoryCount: function ({name}) {
    return new Promise((resolve,reject)=>{
      VersionHistory.getHistoryCount({name}, function (err,data) {
        err ? reject(err) : resolve(data);
      })
    })
  },

  getLastHistory: function ({name, index}) {
    return new Promise((resolve,reject)=>{
      VersionHistory.getLastHistory({name, index}, function (err,data) {
        err ? reject(err) : resolve(data);
      })
    })
  },

  getHistoriesByPage: function ({name, objectId, pageSize}) {
    return new Promise((resolve,reject)=>{
      VersionHistory.getHistoriesByPage({name, objectId, pageSize}, function (err,data) {
        err ? reject(err) : resolve(data);
      })
    })
  },

  getHistoriesBySkip: function ({name, pageNum, pageSize}) {
    return new Promise((resolve,reject)=>{
      VersionHistory.getHistoriesBySkip({name, pageNum, pageSize}, function (err,data) {
        err ? reject(err) : resolve(data);
      })
    })
  }

}